import { PageComponent, html, reactive } from 'nvagir'

import './StudyPlan.less'
import { addPlanModal } from '../../components/PlanModal'
import { addTodoModal } from '../../components/TodoModal'
import StudyPlanLeft from './StudyPlanLeft'
import StudyPlanRight from './StudyPlanRight'
import MainSideBar from '../../components/MainSideBar/MainSideBar'

/** when screen<768,customer choosen switch to todo or plan ,rightHiddenOnPhone mean customer choosen to plan,leftHiddenOnPhone mean customer choosen to todo*/
enum ViewState {
  rightHiddenOnPhone,
  leftHiddenOnPhone,
}

/**
 *
 * @returns return studyPlan component
 */
const StudyPlan: PageComponent = () => {
  // 用于初始化模板和初始化传入参数
  const data = {
    list: [
      {
        title: '学习Node.js',
        comment: '学习Node.js',
        dueDate: '2012/02/02',
        details: [
          {
            title: 'this is one title',
            desc: 'this is one desc',
            completed: false,
          },
          {
            title: 'this is two title',
            desc: 'this is two desc',
            completed: true,
          },
          {
            title: 'this is three title',
            desc: 'this is three desc',
            completed: true,
          },
          {
            title: 'this is four title',
            desc: 'this is four desc',
            completed: true,
          },
        ],
        way: '前端',
        tags: ['JS', 'CSS'] as string[],
      },
      {
        title: '学习Padding.js',
        comment: '学习Padding.js',
        dueDate: '2012/02/02',
        details: [
          {
            title: 'this is one title',
            desc: 'this is one desc',
            completed: false,
          },
        ],
        way: '前端',
        tags: ['JS', 'CSS'] as string[],
      },
    ],
    activeIdx: 0,
    state: ViewState.rightHiddenOnPhone,
  }

  /**
   * make proxyData update ,because the proxyData can't response the change of the child property of data
   */
  const forceReRender = () => {
    proxyData.list = [...proxyData.list]
  }

  /**
   *
   * calc the progress of the active plan
   */

  const calcPer = () => {
    const idx = data.activeIdx
    const todos = data.list[idx].details
    if (todos.length == 0) {
      return 0
    }
    const edTodo = data.list[idx].details.filter(item => item.completed)
    let per = (edTodo.length / todos.length).toFixed(2)
    return Number(per) * 100
  }

  /**
   * change the active plan
   * @param idx
   */
  const changeActive = (idx: number) => {
    proxyData.activeIdx = idx
  }

  /**
   * change current viewState to leftHiddenOnPhone,it mean when the screen<768px,the plan component hidden
   */
  const clickPlanMobile = () => {
    proxyData.state = ViewState.leftHiddenOnPhone
  }

  /**
   * change current viewState to leftHiddenOnPhone,it mean when the screen<768px,the plan component hidden
   */
  const backClickPlan = () => {
    proxyData.state = ViewState.rightHiddenOnPhone
  }

  const rightHiddenOnPhone = () => {
    components.StudyPlanLeft.el.dom.classList.remove('hidden-phone')
    components.StudyPlanRight.el.dom.classList.add('hidden-phone')
  }

  const leftHiddenOnPhone = () => {
    components.StudyPlanLeft.el.dom.classList.add('hidden-phone')
    components.StudyPlanRight.el.dom.classList.remove('hidden-phone')
  }

  const addTodo = () => {
    addTodoModal({
      onClose() {
        console.log('关闭了')
      },
      onConfirm(todo: Todo) {
        // proxy.set
        proxyData.list[proxyData.activeIdx].details = [
          ...proxyData.list[proxyData.activeIdx].details,
          todo,
        ]
        forceReRender()
      },
    })
  }

  const editTodo = (todo: Todo, newTodo: Todo) => {
    const todos = proxyData.list[proxyData.activeIdx].details
    const idx = todos.findIndex(item => item === todo)
    todos[idx] = newTodo
    forceReRender()
  }

  const delTodo = (todo: Todo) => {
    let todos = proxyData.list[proxyData.activeIdx].details
    const idx = todos.findIndex(item => item === todo)
    todos.splice(idx, 1)
    forceReRender()
  }

  const addPlan = () => {
    addPlanModal({
      onClose() {},
      onConfirm(plan) {
        proxyData.list = [...proxyData.list, plan]
      },
    })
  }

  const editPlan = (plan: Plan, newPlan: Plan) => {
    let plans = proxyData.list
    const idx = plans.findIndex(item => item === plan)
    console.log(`idx=${idx}`)
    plans[idx] = newPlan
    forceReRender()
  }

  const delPlan = (plan: Plan) => {
    let plans = proxyData.list
    const idx = plans.findIndex(item => item === plan)
    plans.splice(idx, 1)
    forceReRender()
  }

  /**
   * render todos component
   */
  const renderRight = () => {
    components.StudyPlanRight = StudyPlanRight(
      data.list[data.activeIdx].details,
      calcPer(),
      forceReRender,
      backClickPlan,
      addTodo,
      editTodo,
      delTodo,
    )
    doms.studyPlan.append(components.StudyPlanRight.el.dom)
  }

  /**
   * render Plans component
   */

  const renderLeft = () => {
    components.StudyPlanLeft = StudyPlanLeft(
      data.list,
      data.activeIdx,
      changeActive,
      clickPlanMobile,
      delPlan,
      addPlan,
      editPlan,
    )
    doms.studyPlan.append(components.StudyPlanLeft.el.dom)
  }

  const renderMainSideBar = () => {
    components.MainSideBar = MainSideBar()
    doms.studyPlan.append(components.MainSideBar.el.dom)
  }
  const render = () => {
    doms.studyPlan.innerHTML = ''
    renderLeft()
    renderRight()
    renderMainSideBar()
  }

  const { el, doms, components } = html<
    {
      studyPlan: HTMLElement
    },
    [typeof StudyPlanRight, typeof StudyPlanLeft, typeof MainSideBar]
  >`
    <div class="study-plan" n@name="studyPlan">
      ${StudyPlanLeft(
        data.list,
        data.activeIdx,
        changeActive,
        clickPlanMobile,
        delPlan,
        addPlan,
        editPlan,
      )}
      ${StudyPlanRight(
        data.list[data.activeIdx].details,
        calcPer(),
        forceReRender,
        backClickPlan,
        addTodo,
        editTodo,
        delTodo,
      )}
      ${MainSideBar()}
    </div>
  `

  const proxyData = reactive(data, (p, data) => {
    switch (p) {
      case 'activeIdx':
        render()
      case 'list':
        render()
      case 'state':
        if (data.state == ViewState.leftHiddenOnPhone) {
          leftHiddenOnPhone()
        } else {
          rightHiddenOnPhone()
        }
    }
  })

  return { el }
}

export default StudyPlan
